/* 
 *
 * Copyright (C) 2007, Chad Phillips <chad@chadphillips.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */


#include "mii.h"
#include "wiimote.h"
#include "wiimote_error.h"
#include "wiimote_io.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


//------------------------------------------------------------------------------
//  Function:   save_all_wiimote_data_to_file 
//  Purpose:    Read all save data from the wiimote and write it to the given file
//  Parameters: wiimote, filename
//  Returns: -1 on error, 0 on success
//------------------------------------------------------------------------------
int
save_all_wiimote_data_to_file (wiimote_t * wiimote, const char *filename)
{

  uint8_t data[WIIMOTE_SAVEDATA_SIZE];
  if (wiimote_read (wiimote, WIIMOTE_SAVEDATA_BEGIN, data, WIIMOTE_SAVEDATA_SIZE))
    {
      return WIIMOTE_ERROR;
    }


  FILE *file;
  file = fopen (filename, "wb");
  fwrite (data, sizeof (data[0]), sizeof (data) / sizeof (data[0]), file);
  fclose (file);

  return WIIMOTE_OK;
}

//------------------------------------------------------------------------------
//  Function:   save_mii_to_file 
//  Purpose:    Reads one Mii slot from wiimote and writes it to the given file
//  Parameters: wiimote, filename, slot number
//  Returns: -1 on error, 0 on success
//------------------------------------------------------------------------------
int
save_mii_to_file (wiimote_t * wiimote, const char *filename, int slot)
{

  // The Mii is only 74 bytes long, but we can only read blocks that are
  // multiples of 16.  Make a data block of 80.  
  uint16_t MII_DATA_BLOCK = 80;
  uint8_t data[MII_DATA_BLOCK];

  uint8_t mii_data[WIIMOTE_MII_DATA_BYTES_PER_SLOT];

  if (wiimote_read (wiimote, (slot * WIIMOTE_MII_DATA_BYTES_PER_SLOT) + WIIMOTE_MII_DATA_BEGIN_1, data, MII_DATA_BLOCK))
    {
      return WIIMOTE_ERROR;
    }

  // Copy the first 74 bytes of our data read, discarding the rest
  memcpy(mii_data,data,WIIMOTE_MII_DATA_BYTES_PER_SLOT);

  FILE *file;
  file = fopen (filename, "wb");
  fwrite (data, sizeof (mii_data[0]), sizeof (mii_data) / sizeof (mii_data[0]), file);
  fclose (file);

  return WIIMOTE_OK;
}
